package com.sunwayhorizo.health.business.clinic.emr.template.query;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.jboss.seam.annotations.Name;

import com.sunwayhorizo.health.common.ListUtil;
import com.sunwayhorizo.health.common.StrUtil;
import com.sunwayhorizo.health.hl7.common.Hl7Exception;
import com.sunwayhorizo.health.hl7.rim.Role;
import com.sunwayhorizo.health.hl7.vocabulary.RoleCode;

@Name("TemplateQuery")
@Stateless
public class TemplateQuery implements TemplateQueryLocal
{

    @PersistenceContext(unitName = "sunwayhealth")
    public EntityManager em;


    @SuppressWarnings("unchecked")
    public List<Long> findDocIdByDocName(String fileName) throws Hl7Exception
    {
        StringBuilder jpql = new StringBuilder();
        jpql.append(" select doc.actId from Document doc");
        jpql.append(" where doc.titleTxt='" + fileName + "'");
        List<Long> list = em.createQuery(jpql.toString()).getResultList();
        return list;
    }


    @SuppressWarnings("unchecked")
    public List<Object> findTemplateListByClassIds(List<Long> classIds) throws Hl7Exception
    {
        if (ListUtil.isEmpty(classIds))
            return null;
        StringBuilder sb = new StringBuilder();
        sb.append("select doc.actId, doc.titleTxt,doc.statusCode,doc.levelCodeEtsId,doc.createdBy,doc.creationDate,doc.negationFlag,doc.dcStorageCodeEtsId ");
        sb.append(" from Document doc ");
        sb.append(" where doc.classCode='DOC' ");
        sb.append(" and (");
        for (int i = 0; i < classIds.size(); i++)
        {
            Long classId = (Long) classIds.get(i);
            if (i < classIds.size() - 1)
            {
                sb.append(" doc.levelCodeEtsId=" + classId + " or ");
            }
            else
            {
                sb.append("  doc.levelCodeEtsId=" + classId);
            }
        }
        sb.append(" )");
        List<Object> docs = em.createQuery(sb.toString()).getResultList();
        return docs;
    }


    @SuppressWarnings("unchecked")
    public List<Object> findCustomizeTempListByEmpId(String empId, Long entityId) throws Hl7Exception
    {
        StringBuilder jpql = new StringBuilder();
        jpql.append(" select doc.actId, doc.titleTxt,doc.statusCode,doc.levelCodeEtsId,doc.createdBy,doc.creationDate,doc.negationFlag,doc.dcStorageCodeEtsId ");
        jpql.append(" from Document doc left join doc.prtcptnsActList p ");
        jpql.append(" where doc.classCode='DOC' and doc.levelCodeEtsId =" + entityId + " ");
        jpql.append(" and p.typeCode='TEMPBELPSN' and p.roleParticipation.roleId=" + empId);
        List<Object> docs = em.createQuery(jpql.toString()).getResultList();
        return docs;
    }


    @SuppressWarnings("unchecked")
    public List<Object> findTemplateListByClassTempId(String classEntityId) throws Hl7Exception
    {
        StringBuilder jpql = new StringBuilder();
        jpql.append(" select doc.actId, doc.titleTxt,doc.statusCode,doc.levelCodeEtsId,doc.createdBy,doc.creationDate,doc.negationFlag,doc.dcStorageCodeEtsId");
        jpql.append(" from Document doc");
        jpql.append(" where doc.classCode='DOC' and doc.levelCodeEtsId =" + classEntityId);
        List<Object> docs = em.createQuery(jpql.toString()).getResultList();
        return docs;
    }


    @SuppressWarnings("unchecked")
    public List<Object> findAllHospitalTempleteByEntityId(String classId, String roleType) throws Hl7Exception
    {
        StringBuilder jpql = new StringBuilder();
        String cond = "";
        jpql.append(" select doc.actId, doc.titleTxt,doc.statusCode,doc.levelCodeEtsId,doc.createdBy,doc.creationDate,doc.negationFlag,doc.dcStorageCodeEtsId");
        jpql.append(" from Document doc");
        cond += " where doc.classCode='DOC' and doc.levelCodeEtsId =" + classId;
        if (roleType.equals("1"))
        {
            jpql.append(" left join doc.prtcptnsActList prt");
            cond += " and prt.typeCode='TEMPBELORG'";
        }
        cond += " order by doc.dcStorageCodeEtsId asc";
        List<Object> docs = em.createQuery(jpql.toString() + cond).getResultList();
        return docs;
    }


    @SuppressWarnings("unchecked")
    public List<Object> finddeptTempleteByEntityId(String classId, String deptId) throws Hl7Exception
    {
        StringBuilder jpql = new StringBuilder();
        jpql.append(" select doc.actId, doc.titleTxt,doc.statusCode,doc.levelCodeEtsId,doc.createdBy,doc.creationDate,doc.negationFlag,doc.dcStorageCodeEtsId ");
        jpql.append(" from Document doc left join doc.prtcptnsActList p ");
        jpql.append(" where doc.classCode = 'DOC' and doc.levelCodeEtsId =" + classId + " ");
        jpql.append(" and p.typeCode='TEMPBELDEPT' and p.roleParticipation.roleId=" + deptId);
        List<Object> deptTemplates = em.createQuery(jpql.toString()).getResultList();
        return deptTemplates;
    }


    @SuppressWarnings("unchecked")
    public List<Object> findTemplateListByEntityIdDeptIdWGIds(String classId, String deptId, List<String> workGroupIds) throws Hl7Exception
    {
        StringBuilder jpql = new StringBuilder();
        jpql.append(" select doc.actId, doc.titleTxt,doc.statusCode,doc.levelCodeEtsId,doc.createdBy,doc.creationDate,doc.negationFlag,doc.dcStorageCodeEtsId ");
        jpql.append(" from Document doc left join doc.prtcptnsActList p ");
        jpql.append(" where doc.classCode = 'DOC' and doc.levelCodeEtsId =" + classId + "  ");
        if (StrUtil.isNotEmpty(deptId))
        {
            if (ListUtil.isNotEmpty(workGroupIds))
            {
                jpql.append("and ( (p.typeCode='TEMPBELDEPT' and p.roleParticipation.roleId=" + deptId + ") ");
                jpql.append(" or (p.typeCode='TEMPBELWG' and p.roleParticipation.roleId in :wgIds ) )");
            }
            else
            {
                jpql.append("and p.typeCode='TEMPBELDEPT' and p.roleParticipation.roleId=" + deptId);
            }
        }
        else
        {
            if (ListUtil.isNotEmpty(workGroupIds))
            {
                jpql.append(" and p.typeCode='TEMPBELWG' and p.roleParticipation.roleId in :wgIds");
            }
        }
        Query q = em.createQuery(jpql.toString());
        if (ListUtil.isNotEmpty(workGroupIds))
        {
            q.setParameter("wgIds", workGroupIds);
        }
        List<Object> deptAndWorkGroupTemplates = q.getResultList();
        return deptAndWorkGroupTemplates;
    }


    public Long findTemplateListByClassCode(String classCode) throws Hl7Exception
    {
        if (StrUtil.isEmpty(classCode)) return null;
        StringBuilder jpql = new StringBuilder();
        jpql.append(" select eii.rimCoreEntities.entityId from RimCoreEntyIi eii where eii.extensionTxt='" + classCode + "' ");
        Long entityId = (Long) em.createQuery(jpql.toString()).getSingleResult();
        return entityId;
    }


    @SuppressWarnings("unchecked")
    public List<Long> findTemplateClassIdByFatherId(String fatherId) throws Hl7Exception
    {
        if (StrUtil.isEmpty(fatherId)) return null;
        StringBuilder jpql = new StringBuilder();
        jpql.append(" select r.playerEntities.entityId from Role r ");
        jpql.append(" where r.codeEtsId='" + RoleCode.TEMPCLASS.toString() + "'");
        jpql.append(" and r.scoperEntities.entityId=" + fatherId+ "  ");
        jpql.append(" order by r.playerEntities.entityId asc ");
        List<Long> list = em.createQuery(jpql.toString()).getResultList();
        return list;
    }

    @SuppressWarnings("unchecked")
    public Role findClassRoleByEntId(String entityId) throws Hl7Exception
    {
        if (StrUtil.isEmpty(entityId)) return null;
        StringBuilder jpql = new StringBuilder();
        jpql.append(" select r from Role r ");
        jpql.append(" where r.playerEntities.entityId = " + entityId);
        List<Role> roleList = em.createQuery(jpql.toString()).getResultList();
        Role role = null;
        if(ListUtil.isNotEmpty(roleList)) 
        {
            role = roleList.get(0);  
        }
        return role;
    }


    @SuppressWarnings("unchecked")
    public List<Role> findAllTempClassRoleList() throws Hl7Exception
    {
        StringBuilder jpql = new StringBuilder();
        jpql.append(" select r from Role r ");
        jpql.append(" where r.codeEtsId='" + RoleCode.TEMPCLASS.toString() + "' ");
        jpql.append(" order by r.roleId asc ");
        List<Role> roleList = em.createQuery(jpql.toString()).getResultList();
        return roleList;
    }

    @SuppressWarnings("unchecked")
    public List<Role> findAllTempClassRoleByFatherId(String fatherId) throws Hl7Exception
    {

        StringBuilder jpql = new StringBuilder();
        jpql.append(" select r from Role r ");
        jpql.append(" where r.codeEtsId='" + RoleCode.TEMPCLASS.toString() + "' ");
        jpql.append(" and r.scoperEntities.entityId=" + fatherId+ " ");
        jpql.append(" order by r.playerEntities.entityId asc ");
        List<Role> roleList = em.createQuery(jpql.toString()).getResultList();
        return roleList;
    }

    @SuppressWarnings("unchecked")
    public List<Object> findChildIdsByFatherId(long fatherId) throws Hl7Exception
    {
        StringBuilder jpql = new StringBuilder();
        jpql.append(" select r.roleId from Role r ");
        jpql.append(" where r.codeEtsId='" + RoleCode.TEMPCLASS.toString() + "' ");
        jpql.append(" and r.scoperEntities.entityId=" + fatherId+ " ");
        List<Object> roleIds = em.createQuery(jpql.toString()).getResultList();
        return roleIds;
    }

    public Long findTempClassEntyIdByCode(String classCode) throws Hl7Exception
    {
        if (StrUtil.isEmpty(classCode))  return null;
        StringBuilder jpql = new StringBuilder();
        jpql.append(" select eii.rimCoreEntities.entityId from RimCoreEntyIi eii ");
        jpql.append(" where eii.extensionTxt='" + classCode + "' ");
        Long entityId = (Long) em.createQuery(jpql.toString()).getSingleResult();
        return entityId;
    }

    @SuppressWarnings("unchecked")
    public List<Object> findAllHospitalToAuditorTemp() throws Hl7Exception
    {
        StringBuilder jpql = new StringBuilder();
        jpql.append(" select doc.actId, doc.titleTxt,doc.statusCode,doc.levelCodeEtsId,doc.createdBy,doc.creationDate,doc.negationFlag ");
        jpql.append(" from Document doc left join doc.prtcptnsActList p ");
        jpql.append(" where doc.codeEtsId='TEMPFILE' and doc.statusCode in ('1','4','7') ");
        jpql.append(" and (p.typeCode='TEMPBELORG' or p.typeCode='TEMPBELDEPT' or p.typeCode='TEMPBELWG') ");
        jpql.append(" order by doc.creationDate ");
        List<Object> list = em.createQuery(jpql.toString()).getResultList();
        return list;
    }


    @SuppressWarnings("unchecked")
    public List<Object> findAllDeptToAuditorTemp(String deptRoleId) throws Hl7Exception
    {
        StringBuilder jpql = new StringBuilder();
        jpql.append(" select doc.actId, doc.titleTxt,doc.statusCode,doc.levelCodeEtsId,doc.createdBy,doc.creationDate,doc.negationFlag ");
        jpql.append(" from Document doc left join doc.prtcptnsActList p ");
        jpql.append(" where doc.codeEtsId='TEMPFILE' and doc.statusCode in ('1','4','7') ");
        jpql.append(" and ( p.typeCode='TEMPBELDEPT' and p.roleParticipation.roleId = '"+ deptRoleId + "') ");
        List<Object> list = em.createQuery(jpql.toString()).getResultList();
        return list;
    }


    @SuppressWarnings("unchecked")
    public List<Object> findAllDeptAndWGToAuditorTemp(String deptRoleId, List<String> workGroupRoleIds) throws Hl7Exception
    {
        StringBuilder jpql = new StringBuilder();
        jpql.append(" select doc.actId, doc.titleTxt,doc.statusCode,doc.levelCodeEtsId,doc.createdBy,doc.creationDate,doc.negationFlag ");
        jpql.append(" from Document doc left join doc.prtcptnsActList p ");
        jpql.append(" where doc.codeEtsId='TEMPFILE' and doc.statusCode in ('1','4','7')  and (");
        jpql.append(" ( p.typeCode='TEMPBELDEPT' and p.roleParticipation.roleId = '" + deptRoleId + "') ");
        if (ListUtil.isNotEmpty(workGroupRoleIds))
        {
            jpql.append(" or (p.typeCode='TEMPBELWG' and p.roleParticipation.roleId in :wgIds ) ");
        }
        jpql.append(" ) order by doc.creationDate ");
        Query q = em.createQuery(jpql.toString());
        if (ListUtil.isNotEmpty(workGroupRoleIds))
        {
            q.setParameter("wgIds", workGroupRoleIds);
        }
        List<Object> list = q.getResultList();
        return list;
    }


    @SuppressWarnings("unchecked")
    public List<Object> findAllHospitalAlreadyAuditorTemp() throws Hl7Exception
    {
        StringBuilder jpql = new StringBuilder();
        jpql.append(" select doc.actId, doc.titleTxt,doc.statusCode,doc.levelCodeEtsId,doc.createdBy,doc.creationDate,doc.negationFlag ");
        jpql.append(" from Document doc left join doc.prtcptnsActList p ");
        jpql.append(" where doc.codeEtsId='TEMPFILE' and doc.statusCode in ('2','5','8') ");
        jpql.append(" and (p.typeCode='TEMPBELORG' or p.typeCode='TEMPBELDEPT' or p.typeCode='TEMPBELWG') ");
        jpql.append(" order by doc.creationDate ");
        List<Object> list = em.createQuery(jpql.toString()).getResultList();
        return list;
    }


    @SuppressWarnings("unchecked")
    public List<Object> findAllDeptAlreadyAuditorTemp(String deptRoleId) throws Hl7Exception
    {
        StringBuilder jpql = new StringBuilder();
        jpql.append(" select doc.actId, doc.titleTxt,doc.statusCode,doc.levelCodeEtsId,doc.createdBy,doc.creationDate,doc.negationFlag ");
        jpql.append(" from Document doc left join doc.prtcptnsActList p ");
        jpql.append(" where doc.codeEtsId='TEMPFILE' and doc.statusCode in ('2','5','8') ");
        jpql.append(" and ( p.typeCode='TEMPBELDEPT' and p.roleParticipation.roleId = '"+ deptRoleId + "') ");
        List<Object> list = em.createQuery(jpql.toString()).getResultList();
        return list;
    }

    @SuppressWarnings("unchecked")
    public List<Object> findAllDeptAndWGAlreadyAuditorTemp(String deptRoleId, List<String> workGroupRoleIds) throws Hl7Exception
    {
        StringBuilder jpql = new StringBuilder();
        jpql.append(" select doc.actId, doc.titleTxt,doc.statusCode,doc.levelCodeEtsId,doc.createdBy,doc.creationDate,doc.negationFlag ");
        jpql.append(" from Document doc left join doc.prtcptnsActList p ");
        jpql.append(" where doc.codeEtsId='TEMPFILE' and doc.statusCode in ('2','5','8') and (");
        jpql.append("   ( p.typeCode='TEMPBELDEPT' and p.roleParticipation.roleId = '" + deptRoleId + "') ");
        if (ListUtil.isNotEmpty(workGroupRoleIds))
        {
            jpql.append(" or (p.typeCode='TEMPBELWG' and p.roleParticipation.roleId in :wgIds ) ");
        }
        jpql.append(" ) order by doc.creationDate ");
        Query q = em.createQuery(jpql.toString());
        if (ListUtil.isNotEmpty(workGroupRoleIds))
        {
            q.setParameter("wgIds", workGroupRoleIds);
        }
        List<Object> list = q.getResultList();
        return list;
    }
    
    public String getBaseQuery() throws Hl7Exception
    {
        
        return null;
    }

}
